<?php

/**
 * 商品控制器
 */
namespace Custom\Controller;
use Think\Controller;
class GoodsController extends UserController {

    function __construct()
    {
        parent::__construct();
        $this->M_goods = M('Goods');
        $this->M_cate = M('Goods_cate');
        $this->M_goods_img = M('Goods_img');
        $this->M_goods_spec = M('Goods_spec');
        $this->M_goods_item = M('Goods_spec_item');
        $this->M_goods_option = M('Goods_spec_option');
    }

    /**
     *  商品列表
     */
    public function index(){
        if($this->s_id){
            if(IS_GET&&$_GET['id']&&$_GET['maodian']=='x'){
                $deletsql = "goods_id in (".implode(",",$_GET['id']).")";
                $deletsql.= " and c_id=".$this->c_id;
                $info = $this->M_goods->where($deletsql)->find();
                if($info){
                    $this->M_goods->where($deletsql)->delete();
                }
            }
            $where = 'g.s_id = '.$this->s_id;
            if($_GET['goods_name']){
                $this->assign('goods_name',$_GET['goods_name']);
                $where .= ' AND goods_name LIKE\'%'.$_GET['goods_name'].'%\'';
            }
            if($_GET['goods_cate_id']){
                $this->assign('goods_cate_id',$_GET['goods_cate_id']);
                $where .= ' AND g.goods_cate_id = '.$_GET['goods_cate_id'];
            }
            $count = $this->M_goods->where($where)->join('as g left join sp_goods_cate as c ON g.goods_cate_id = c.goods_cate_id')->count();
            $page_num = $this->is_page($count);
            $goods_list = $this->M_goods->where($where)->join('as g left join sp_goods_cate as c ON g.goods_cate_id = c.goods_cate_id')->order('add_time desc')->limit($page_num->firstRow.','.$page_num->listRows)->field('goods_cate_name,goods_name,default_img,price,goods_id,g.is_show,is_hot,is_home,g.add_time,g.sort')->select();
            $this->assign('list',$goods_list);
            $this->assign("count",$count);
        }
        $this->display();
    }

    /**
     *  删除单一商品
     */
    public function delete(){
        $where['goods_id'] = (int)$_GET['id'];
        $where['c_id'] = $this->c_id;
        $info = $this->M_goods->where($where)->find();
        if($info){
            $result = $this->M_goods->where($where)->delete();
            if ($result) $this->ajaxReturn(array('result'=>'tp'));
            else $this->ajaxReturn(array('result'=>'break'));
        }
        else{
            $this->ajaxReturn(array('result'=>'break'));
        }
    }

    /**
     *  是否显示
     */
    public function is_show(){
        $id = $where['goods_id'] = (int)$_GET['id'];
        $where['c_id'] = $this->c_id;

        $info = $this->M_goods->find($id);
        $is_show = $info['is_show']?0:1;
        $this->M_goods->is_show = $is_show;
        $this->M_goods->where($where)->save();
        $is_show?$this->ajaxReturn(array('result'=>'yes')):$this->ajaxReturn(array('result'=>'no'));
    }

    /**
     *  是否首页
     */
    public function is_home(){
        $id = $where['goods_id'] = (int)$_GET['id'];
        $where['c_id'] = $this->c_id;

        $info = $this->M_goods->find($id);
        $is_home = $info['is_home']?0:1;
        $this->M_goods->is_home = $is_home;
        $this->M_goods->where($where)->save();
        $is_home?$this->ajaxReturn(array('result'=>'yes')):$this->ajaxReturn(array('result'=>'no'));
    }

    /**
     * 是否热门
     */
    public function is_hot(){
        $id = $where['goods_id'] = (int)$_GET['id'];
        $where['c_id'] = $this->c_id;

        $info = $this->M_goods->find($id);
        $is_hot = $info['is_hot']?0:1;
        $this->M_goods->is_hot = $is_hot;
        $this->M_goods->where($where)->save();
        $is_hot?$this->ajaxReturn(array('result'=>'yes')):$this->ajaxReturn(array('result'=>'no'));
    }

    /**
     *  添加修改商品
     */
    public function edit(){
        $id = (int)$_GET['id'];


// exit;
        if(!$this->s_id){
            die($this->error('请先选择门店！',U('goods/index')));
        }else{
            if(IS_POST){
                //添加,修改商品
                $this->M_goods->goods_name = $_POST['goods_name'];
                $this->M_goods->goods_cate_id = (int)$_POST['goods_cate_id'];
                $this->M_goods->price = $_POST['option_price'][0]?$_POST['option_price'][0]:0;
                $this->M_goods->market_price = $_POST['option_price'][0]?$_POST['option_price'][0]:0;
                $this->M_goods->stock = (int)$_POST['stock']?$_POST['stock']:0;
                $this->M_goods->is_show = (int)$_POST['is_show']?$_POST['is_show']:0;
                $this->M_goods->is_home = (int)$_POST['is_home']?$_POST['is_home']:0;
                $this->M_goods->is_hot = (int)$_POST['is_hot']?$_POST['is_hot']:0;
                $this->M_goods->goods_introduce = $_POST['goods_introduce'];
                $this->M_goods->sort = (int)$_POST['sort']?$_POST['sort']:0;
                $this->M_goods->goods_describe = $_POST['goods_describe'];
                if($_POST['goods_type']==1){
                    $this->M_goods->goods_type = 1;
                }else{
                    $this->M_goods->goods_type = 0;
                }

                $upload = new \Think\Upload();
                $upload->maxSize = 2145728 ;
                $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
                $upload->rootPath = './';
                $upload->savePath = './Uploads/'.$this->c_id.'/default_img/'.$this->uid.'/';
                $upload->saveName = 'my_filename';
                $img_info   =   $upload->upload();
                if($img_info){
                    $img = $img_info['default_img']['savepath'].$img_info['default_img']['savename'];
                    $imgSmall = $img_info['default_img']['savepath'].'small'.$img_info['default_img']['savename'];
                    $default_img = $img_info['default_img']['savepath'].'midsize'.$img_info['default_img']['savename'];
                    $image = new \Think\Image(); //实例化TP自带的图片类
                    $image->open($img);
                    $image->thumb(300, 300,\Think\Image::IMAGE_THUMB_CENTER)->save($imgSmall);
                    $image->thumb(600, 600,\Think\Image::IMAGE_THUMB_CENTER)->save($default_img);
                    $this->M_goods->default_img = $default_img;
                    $this->M_goods->cover_small = $imgSmall;
                }else{
                    //if($upload->getError()!='L("meiyouwenjian")') $this->error($upload->getError());
                }

                if($id){
                    $result = $this->M_goods->where(array('goods_id'=>$id))->save();
                    if($_POST['myimg']){
                        foreach($_POST['myimg'] as $val){
                            $this->M_goods_img->goods_id = $id;
                            $this->M_goods_img->goods_imgurl = $val;
                            $this->M_goods_img->add();
                        }
                        $result = true;
                    }
                }else{
                    $this->M_goods->add_time = time();
                    $this->M_goods->c_id = $this->c_id;
                    $this->M_goods->s_id = $this->s_id;
                    $result = $this->M_goods->add();
                    if($_POST['myimg']){
                        foreach($_POST['myimg'] as $val){
                            $this->M_goods_img->goods_id = $result;
                            $this->M_goods_img->goods_imgurl = $val;
                            $this->M_goods_img->add();
                        }
                    }
                }

                if($id){
                    $option = $this->M_goods_option->where("goods_id=$id AND checked=0")->select();
                    $option_id = $_POST['option_id'] ;

                    foreach ($option_id as $k => $value) {
                        $find = false;
                        foreach ($option as $key => $v) {
                            if($v['goods_option_id'] == $value){
                                $find = true;
                                continue;
                            }
                        }
                        if($find){
                            //修改规格
                            $save = array(
                                'option_title' => $_POST['option_title'][$k],
                                'price' => $_POST['option_price'][$k],
                                'stock' => $_POST['stock'][$k],
                                 );
                            $this->M_goods_option->where("goods_option_id=$value")->save($save);
                        }else{
                            //添加规格
	                        $add = array(
	                            'c_id' => $this->c_id,
	                            's_id' => $this->s_id,
	                            'goods_id' => $id,
	                            'option_title' => $_POST['option_title'][$k],
	                            'price' => $_POST['option_price'][$k],
	                            'stock' => $_POST['stock'][$k],
	                             );
	                        $this->M_goods_option->add($add);
                        }

                    }
                }else{
                    //添加规格
                    $option = $_POST['option_id'];
                    foreach ($option as $key => $v) {
                        $add = array(
                            'c_id' => $this->c_id,
                            's_id' => $this->s_id,
                            'goods_id' => $result,
                            'option_title' => $_POST['option_title'][$key],
                            'price' => $_POST['option_price'][$key],
                            'stock' => $_POST['stock'][$key],
                             );
                        $this->M_goods_option->add($add);
                    }
                }
                $this->success(L('adsuccess'),U('goods/index'));
            }
            else{
                //编辑
                $cate_where['c_id'] = $this->c_id;
                $cate_where['s_id'] = $this->s_id;
                $cate_where['p_id'] = 0;
                $cate_list = $this->M_cate->where($cate_where)->order('sort desc')->select();

                $this->assign('cate_list',$cate_list);

                if($id){
                    $info = $this->M_goods->find($id);
                    $this->assign('info',$info);
                    $img_list = $this->M_goods_img->where("goods_id = ".$id)->select();
                    $this->assign('img_list',$img_list);
                    //规格列表
                    $option = $this->M_goods_option->where("goods_id=$id AND checked=0")->select();
                    //p($option);
                    $this->assign('option',$option);

                }else{
                    $info['is_show'] = 1;
                    $info['sort'] = 0;
                    $this->assign('info',$info);
                }




            }
        }
        $this->display();
    }
    public function delete_option(){
    	$id = $_POST['id'];
        $save = array(
        	'checked' => 1,
         );
	    $this->M_goods_option->where("goods_option_id=$id")->save($save);
    }
    /**
     * 多图上传
     */
    public function zyUpdate(){
        error_reporting(E_ALL ^ E_NOTICE);
        mb_http_input("utf-8");
        mb_http_output("utf-8");

        $c_id = $this->s_id;
        $save_path = "./Uploads/";
        $save_url = "/Uploads/";
        $ext_arr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
        $max_size = 1024*4096;
        //$save_path = realpath($save_path) . '/';

        if (empty($_FILES) === false) {
            $file_name = $_FILES['fileList']['name'];
            $tmp_name = $_FILES['fileList']['tmp_name'];
            $file_size = $_FILES['fileList']['size'];//'L("failed")'

            if (@is_dir($save_path) === false) exit('L("failed1")');
            if (@is_writable($save_path) === false) exit(L('failed2'));
            if (@is_uploaded_file($tmp_name) === false) exit(L('failed3'));
            if ($file_size > $max_size) {
                exit(L('failed4'));
            }
            $temp_arr = explode(".", $file_name);
            $file_ext = array_pop($temp_arr);
            $file_ext = trim($file_ext);
            $file_ext = strtolower($file_ext);
            if (in_array($file_ext, $ext_arr) === false) exit(L('failed5'));
            $ymd = date("Ymd");
            $save_path .= $c_id.'/'.$ymd . "/";
            $save_url .= $c_id.'/'.$ymd . "/";
            if (!file_exists($save_path)) mkdir($save_path);
            $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
            $file_path = $save_path.$new_file_name;
            @chmod($file_path, 0644);
            if (move_uploaded_file($tmp_name, $file_path) === false) {
                exit(L('failed6'));
            }
            $file_url = $save_url.$new_file_name;
            $fileName = uniqid('image',true);
            define('IN_CZBD',true);
            $new_pic_path=$file_path;

            $img1="$file_url";
            echo "<img src='".$img1."' onclick='return del(1,0,this)'>
            <input type='hidden' name='myimg[]' value='".$img1."' />";
        }
    }

    /**
     *  删除单一图片
     */
    public function delpic(){
        $where['goods_img_id'] = (int)$_GET['id'];
        $where['goods_id'] = (int)$_GET['goods_id'];

        if($where['goods_img_id']&&$where['goods_id']){
            $info = $this->M_goods_img->where($where)->find();
            if($info){
                $result = $this->M_goods_img->where($where)->delete();
                if ($result) $this->ajaxReturn(array('result'=>'true1'));
            }
        }else if($_GET['id']==1&&$where['goods_id']==0){
            $this->ajaxReturn(array('result'=>'true2'));
        }
    }

}